package com.danbay.framework.kafka.coap;

import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * CoAP消息序号
 *
 * @author SJG
 *         2017/11/13.
 */
public class CoAPMID {

    private static int prefix= RandomUtils.nextInt(1,6);
    private static int maxSequence=5000;

    private static AtomicInteger sequenceAto = new AtomicInteger(0);

    /**
     * 取下一个序号
     * 1~65535
     * @return 序号
     */
    public static int getNextMID() {
        int increaseId= sequenceAto.incrementAndGet();
        int token = prefix*10000+increaseId;
        //例id:65535
        //如果token大于5000从1开始
        if(increaseId>=maxSequence){
            sequenceAto.compareAndSet(increaseId,0);
        }
        return token;
    }
}
